/**
作者:yanzg
*/
import axios from 'axios'
import Cookies from 'js-cookie'
// import store from '@/store/index.js'

const user = {
    namespaced: true,
    state: {
        token: ''
    },
    mutations: {
        setToken (state, token) {
            state.token = token
        }
    },
    actions: {
        login ({ commit }, userInfo) {
            const { username, password } = userInfo
            return axios.post(`/account/api/login/`, { username: username.trim(), password: password }).then(response => {
                const { data } = response.data
                // console.log(data.token)
                commit('setToken', data.token)
                Cookies.set('sops_token', data.token)
                // console.log(data)
                // if (data.result) {
                //     console.log(data.token)
                //     commit('setToken', data.token)
                //     Cookies.set('sops_token', data.token)
                // }
                return response.data
            })
        },
        logout ({ commit }, data) {
            return axios.get('/account/api/logout/').then((response) => {
                commit('setToken', '')
                Cookies.remove('sops_token')
                return response.data
            })
        },
        login2 ({ commit }, userInfo) {
            const { username, password } = userInfo
            // Promise异步请求
            return new Promise((resolve, reject) => {
                axios.post(`/account/api/login/`, { username: username.trim(), password: password }).then(response => {
                    const { data } = response.data
                    console.log(data.token)
                    commit('setToken', data.token)
                    Cookies.set('sops_token', data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        }

    }
}
export default user
